<template>
  <div class="homework-comparison">
    <main class="homework-comparison__main">
      <div v-show="isShowOrigin" class="origin">
        <header>原题</header>
        <DrawingBoard
          :current-mode="currentMode"
          ref="drawingBoardRef"
          @mouse-down="questionMouseDown"
          @touch-start="questionMouseDown"
        >
          <template #content>
            <main>
              <RbQuestion :questionData="questionData" :option="rbqOption">
              </RbQuestion>
            </main>
          </template>
        </DrawingBoard>
      </div>
      <div class="response">
        <header>
          第{{ commentStore.currentQuestion.questionIndex }}题 ｜ 对比讲解
        </header>
        <main :class="{ half: isShowOrigin }">
          <div
            class="list-item"
            v-for="(item, index) in allList.selectedStudent"
            :class="{
              'full-none':
                amplify.isFull && amplify.item.student_id !== item.student_id,
              full:
                amplify.isFull && amplify.item.student_id === item.student_id
            }"
            :key="index"
          >
            <comparison-item
              ref="fullContent"
              :selectedStudent="allList.selectedStudent"
              :allStudentList="allList.allStudent"
              :total="allList.filteredStudent.length"
              :content="item"
              :is-full-screen="
                amplify.isFull && amplify.item.student_id === item.student_id
              "
              :current-mode="currentMode"
              :index="index"
              @full-screen="fullScreen"
              @change-student="changeStudent($event, index)"
              @mouse-down="mouseDown"
              @touch-start="mouseDown"
            />
          </div>
        </main>
      </div>
    </main>
    <footer>
      <div class="operate">
        <div
          @click="changeOrigin"
          class="show-origin"
          :class="{ active: isShowOrigin }"
        >
          <label class="show-origin__icon"></label>
          <span class="show-origin__desc">查看原题</span>
        </div>
        <div @click="goBack" class="back">
          <label class="back__icon"></label>
          <span class="back__desc">返回</span>
        </div>
      </div>
    </footer>
    <SketchpadTools @draw="draw" @revert="revert"></SketchpadTools>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, reactive, watch, nextTick } from 'vue'
import { getCompareList, getAllStudents } from '@/apis/comment/index'
import { useComment } from '@/stores/comment'
import ComparisonItem from './student-compare/ComparisonItem.vue'
import DrawingBoard from './components/DrawingBoard.vue'
import RbQuestion from '@ebag/rb-question-vue3'
import { useRouter } from 'vue-router'
import { ContentInterface } from './constant'
import SketchpadTools from './components/SketchpadTools.vue'

// 撤销栈
const undoStack = ref([])
// 恢复栈
const redoStack = ref([])
const drawingBoardRef = ref()
const currentMode = ref('select')
const router = useRouter()
const commentStore = useComment()
const { homeworkId, currentClass, currentQuestion, studentIds } = useComment()
const isShowOrigin = ref(false)

const fullContent = ref()
const allList = reactive({
  selectedStudent: [],
  allStudent: [],
  filteredStudent: []
})
const rbqOption = ref({
  host: {
    resourceHost: 'https://contres.readboy.com/' // 静态资源(图片、音频等)服务器域名
  },
  displayAnswer: false, // 是否显示题目答案，显示答案时不能作答
  interactive: false, // 是否可作答
  readonly: true, // 可作答时是否只读（只显示之前的作答情况但不能改）
  // answerColor?: string; // 答案颜色，值为css颜色声明
  // enableContentFold?: boolean; // 是否启用题干折叠，默认不启用
  enableSolution: false, // 是否显示答案和解析，默认不显示
  fontSize: '36px'
})

const amplify = reactive({
  item: {
    answer_url: '',
    student_id: '',
    student_name: ''
  },
  isFull: false
})
const getList = async () => {
  const params = {
    question_id: currentQuestion.question_id,
    class_id: currentClass.class_id,
    homework_id: homeworkId,
    student_ids: JSON.stringify(studentIds)
  }
  const {
    data: { list }
  } = await getCompareList(params)
  allList.selectedStudent = list || []
}

const questionData = computed(() => {
  const detail = commentStore.currentQuestion.questionDetail
  const res = {
    typeDetail: detail.type || detail.category,
    data: detail
  }
  return res
})

const changeOrigin = () => {
  isShowOrigin.value = !isShowOrigin.value
}
const goBack = () => {
  router.go(-1)
}

const fullScreen = content => {
  amplify.isFull = !amplify.isFull
  amplify.item = content
  if (amplify.isFull) {
    const i = allList.allStudent.findIndex(
      item1 => item1.student_id === content.student_id
    )
    if (i > -1) {
      allList.allStudent.splice(i, 1)
      allList.allStudent.unshift(content)
    }
  }
}

watch(
  () => isShowOrigin.value,
  val => {
    nextTick(() => {
      if (val && drawingBoardRef.value) {
        drawingBoardRef.value.createCanvas()
        drawingBoardRef.value.draw(currentMode.value)
      }
    })
  }
)

// 获取全部学生列表
const getStudentsList = async () => {
  const params = {
    question_id: +currentQuestion.question_id,
    class_id: currentClass.class_id,
    homework_id: +homeworkId,
    question_type: +(currentQuestion.question_type || 0)
  }
  const { data } = await getAllStudents(params)
  allList.allStudent = []
  if (data.subject_list) {
    allList.allStudent = [...data.subject_list]
  } else if (data.object_list) {
    data.object_list.forEach(item1 => {
      const list = item1.students
      if (list)
        list.forEach(item2 => {
          allList.allStudent.push(item2)
        })
    })
  }
}

const changeStudent = (item, index) => {
  // 非全屏切换
  if (index === 0 || (index && index > 0)) {
    const flag = allList.selectedStudent.findIndex(
      item1 => item1.student_id === item.prev.student_id
    )
    allList.selectedStudent.splice(flag, 1, item.content)
  } else {
    amplify.item = allList.allStudent[item.index]
  }
}

const mouseDown = index => {
  undoStack.value.push(index)
}

const draw = type => {
  currentMode.value = type
  drawingBoardRef.value && drawingBoardRef.value.draw(type)
  if (fullContent.value) {
    fullContent.value.forEach(item => {
      item.draw(type)
    })
  }
}

const questionMouseDown = () => {
  undoStack.value.push('question')
}

const revert = type => {
  console.log('revert', type)
  if (fullContent.value) {
    // 删除
    if (type === 'delete') {
      fullContent.value.forEach(item => {
        item.revert(type)
      })
      drawingBoardRef.value && drawingBoardRef.value.revert(type)
      undoStack.value = []
      redoStack.value = []
    } else if (type === 'recover') {
      // 恢复
      if (redoStack.value.length <= 0) return
      const currentIndex = redoStack.value.at(-1)
      if (currentIndex === 'question') {
        drawingBoardRef.value.revert(type)
      } else {
        const current = fullContent.value[redoStack.value.at(-1)]
        current.revert(type)
      }
      undoStack.value.push(redoStack.value.pop())
    } else {
      // 撤销
      if (undoStack.value.length <= 0) return
      const currentIndex = undoStack.value.at(-1)
      if (currentIndex === 'question') {
        drawingBoardRef.value.revert(type)
      } else {
        const current = fullContent.value[undoStack.value.at(-1)]
        current.revert(type)
      }
      redoStack.value.push(undoStack.value.pop())
    }
  }
}

onMounted(async () => {
  await getList()
  await getStudentsList()
})
</script>
<style lang="less" scoped>
.homework-comparison {
  position: relative;
  overflow-y: hidden;
  background: rgba(25, 43, 42, 1);
  width: 100vw;
  height: 100vh;

  &__main {
    display: flex;
    &::-webkit-scrollbar {
      display: none;
    }

    .origin {
      :deep(*) {
        // overflow-x: hidden !important;
        &::-webkit-scrollbar {
          display: none;
        }
      }
      flex: 1;
      height: 100vh;
      overflow-y: auto;
      margin-bottom: 120px;
      &::-webkit-scrollbar {
        display: none;
      }

      header {
        color: #fff;
        padding: 32px;
        font-size: 20px;
        font-weight: 700;
      }

      main {
        padding: 0 0 128px 32px;
        height: max-content;
        overflow: auto;
        &::-webkit-scrollbar {
          display: none;
        }
      }

      :deep(.rb-question) {
        padding: 0;
        * {
          color: rgba(255, 255, 255, 0.9);
        }

        :deep(*) {
          img {
            background: #fff !important;
          }
        }

        p {
          margin-top: 0;
        }
        .content-container {
          background: inherit;
          padding: 0;
        }

        .option-list-choice {
          padding: 0;
        }
      }
    }
  }

  .response {
    display: flex;
    flex-direction: column;
    flex: 1;
    height: 100vh;
    padding-bottom: 116px;
    overflow-y: auto;
    &::-webkit-scrollbar {
      display: none;
    }
    header {
      padding: 32px 32px 20px 32px;
      color: #fff;
      font-size: 20px;
      font-weight: 700;
    }

    main {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      padding: 0 58px;
      gap: 24px;

      &.half {
        padding: 0 32px;
      }
      .list-item {
        width: 890px;
        height: 422px;
        background: rgba(217, 217, 217, 0.42);

        &.full-none {
          position: absolute;
          left: -100%;
        }

        &.full {
          height: calc(100vh - 200px);
          width: 100vw;
        }
      }
    }
  }

  footer {
    .operate {
      z-index: 1000;
      position: fixed;
      bottom: 0;
      right: 0;
      display: flex;
      align-items: center;
      gap: 4px;
      justify-content: center;
      background: #fff;
      border-radius: 24px;
      height: 88px;
      width: 194px;

      label {
        display: inline-block;
        width: 34px;
        height: 34px;
      }

      .show-origin,
      .back {
        padding: 3px 15px;
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;

        &:hover {
          background: rgba(51, 202, 164, 1);
          border-radius: 12px;
          * {
            color: #fff;
          }
        }
        &__desc {
          color: rgba(4, 11, 26, 0.75);
        }
      }

      .show-origin {
        &__icon {
          background: url('@/assets/images/comment/show-origin.png') no-repeat
            center/cover;
        }

        &:hover {
          .show-origin__icon {
            background: url('@/assets/images/comment/show-origin-hover.png')
              no-repeat center/cover;
          }
        }
      }

      .back {
        &__icon {
          background: url('@/assets/images/comment/return.png') no-repeat
            center/cover;
        }

        &:hover {
          .show-origin__icon {
            background: url('@/assets/images/comment/show-origin-hover.png')
              no-repeat center/cover;
          }

          .back__icon {
            background: url('@/assets/images/comment/return-hover.png')
              no-repeat center/cover;
          }
        }
      }

      .active {
        border-radius: 12px;
        background: rgba(0, 189, 141, 1);
        * {
          color: #fff;
        }

        &.show-origin {
          .show-origin__icon {
            background: url('@/assets/images/comment/show-origin-hover.png')
              no-repeat center/cover;
          }

          &__desc {
            color: #fff;
          }
        }

        &.back {
          .back__icon {
            background: url('@/assets/images/comment/return-hover.png')
              no-repeat center/cover;
          }

          &__desc {
            color: #fff;
          }
        }
      }
    }
  }
}
</style>
